import $C from './config.js'
//import $C from './common/config.js';

export default { 
	async post(url, param,yanci=false) {
		if(yanci){ 
			uni.showLoading({
				title:'加载中'
			})
			setTimeout(()=>{
				uni.hideLoading()
			},3000)			
		}
		const res = await this.uni_request(url,param,'post')  
		if(yanci){
			setTimeout(()=>{
				uni.hideLoading()
			},200)	
		}
		return res;
	},
	async get(url, param,yanci=false) {
		if(yanci){ 
			uni.showLoading({
				title:'加载中'
			})
			setTimeout(()=>{
				uni.hideLoading()
			},3000)			
		}
		const res = await this.uni_request(url,param,'get') 
		if(yanci){
			setTimeout(()=>{
				uni.hideLoading()
			},200)
		}
		return res;
	}, 
	async put(url, param) {
		const res = await this.uni_request(url,param,'put') 
		return res;
	},
	 async configs(yanci=false) {
	 	if(yanci){ 
	 		uni.showLoading({
	 			title:'加载中'
	 		})
	 		setTimeout(()=>{
	 			uni.hideLoading()
	 		},3000)			
	 	}
		let url = 'api/configs'
		let token = uni.getStorageSync('token')
		if(token){
			let param = {token: token}
			const res = await this.uni_request(url,param,'post')  
			if(yanci){
				setTimeout(()=>{
					uni.hideLoading()
				},200)	
			}
			uni.setStorageSync('switch',res.data)
			return res.data;
		}else{
			return false;
		}
		
	 },
	uni_request(url,param,method,again_quest=false) {
		const that=this
	    return new Promise((cback, reject) => {
	    	uni.request({
	    		url: $C.api_url + url,
	    		data: param,
	    		method:method,
	    		header: {
					token:uni.getStorageSync("token")  	    		 	    			
	    		},
	    	}).then(data => { 
	    		var [error, res] = data;
	    		var res_code = res.statusCode.toString(); 
	    		if (res_code.charAt(0) == 2) { 
	    			if(res_code==200){
	    				console.log('200',url)
	    				cback(res.data); 
	    			}else{
						console.log('201',url)
						uni.showToast({
							title:res.data.msg,
							icon:'none'
						})
					}
				}else{
					if(res_code==401){
						//登录失效
						console.log('401',url) 
						if(again_quest){
											
						}else{
							console.log('再次登陆仍然失败',url)
						} 
					}else{
						console.log('400/500',url,error,res)
						uni.showToast({
							title:res.data.msg?res.data.msg:'请求异常',
							icon:'none'
						})
					}
				}	
			}).catch(err => { 
				console.log('catch:',err);					 
			})
		})	
	}, 
	//获取token
	getToken() {
		return uni.getStorageSync("token")
	},
	//判断是否登录
	isLogin() {
		return uni.getStorageSync("token") ? true : false
	},
	//跳转页面，校验登录状态
	href(url,type=1) {
		if (type == 1) {
			uni.navigateTo({
				url: url
			})
		} else if(type == 2) {
			uni.switchTab({
			    url: url
			});
		}else if(type == 3){
			uni.redirectTo({
					url: url
			})
		}
	}

}
